<%@ page import="java.sql.*" %>
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
  <title>个人信息</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      background-color: #f4f4f4;
      padding: 20px;
      margin-bottom: 80px;
    }

    .header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      padding-bottom: 10px;
      border-bottom: 1px solid #ddd;
    }

    .username {
      font-size: 20px;
      font-weight: bold;
    }

    .role-tag {
      font-size: 14px;
      color: #f44336;
      margin-left: 5px;
    }

    .edit-btn {
      background-color: #4CAF50;
      color: white;
      border: none;
      padding: 8px 15px;
      border-radius: 4px;
      cursor: pointer;
    }

    .edit-btn:hover {
      background-color: #45a049;
    }

    .history-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px;
      background-color: #e7e7e7;
      cursor: pointer;
      margin-top: 20px;
    }

    .history-content {
      display: none;
      margin-top: 10px;
    }

    .logout-btn {
      background-color: #f44336;
      color: white;
      border: none;
      padding: 8px 15px;
      border-radius: 4px;
      cursor: pointer;
      margin-top: 20px;
      display: block;
      width: 100%;
    }

    .logout-btn:hover {
      background-color: #d32f2f;
    }

    /* 模态框样式 */
    .modal {
      display: none;
      position: fixed;
      z-index: 1001;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0,0,0,0.4);
    }

    .modal-content {
      background-color: #fefefe;
      margin: 15% auto;
      padding: 20px;
      border: 1px solid #888;
      width: 50%;
      border-radius: 5px;
    }

    .close {
      color: #aaa;
      float: right;
      font-size: 28px;
      font-weight: bold;
      cursor: pointer;
    }

    .close:hover {
      color: black;
    }

    .form-group {
      margin-bottom: 15px;
    }

    .form-group label {
      display: block;
      margin-bottom: 5px;
    }

    .form-group input {
      width: 100%;
      padding: 8px;
      box-sizing: border-box;
      border: 1px solid #ddd;
      border-radius: 4px;
    }

    .save-btn {
      background-color: #4CAF50;
      color: white;
      border: none;
      padding: 10px 15px;
      border-radius: 4px;
      cursor: pointer;
      width: 100%;
    }

    .save-btn:hover {
      background-color: #45a049;
    }

    table {
      width: 极速;
      border-collapse: collapse;
      margin-top: 20px;
      background-color: white;
      box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
    }

    th, td {
      padding: 10px;
      text-align: center;
      border: 1px solid #ccc;
    }

    th {
      background-color: #f0f0f0;
    }

    .delete-btn {
      background-color: #f44336;
      color: white;
      border: none;
      padding: 极速px 10px;
      border-radius: 3px;
      cursor: pointer;
      transition: background-color 0.3s;
    }

    .delete-btn:hover {
      background-color: #d32f2f;
    }

    /* 底部导航栏 */
    .bottom-nav {
      position: fixed;
      bottom: 0;
      left: 0;
      width: 100%;
      height: 60px;
      background-color: #333;
      display: flex;
      justify-content: space-around;
      align-items: center;
      color: white;
      font-size: 16px;
      z-index: 1000;
    }

    .bottom-nav a {
      color: white;
      text-decoration: none;
      flex: 1;
      text-align: center;
    }

    .bottom-nav a:hover {
      text-decoration: underline;
    }
  </style>
</head>
<body>

<%
  String currentUsername = (String) session.getAttribute("username");
  String currentRole = (String) session.getAttribute("user_role");

  // 处理查看其他用户的情形
  String viewUsername = request.getParameter("username");
  String username = currentUsername;
  if (viewUsername != null && "admin".equals(currentRole)) {
    // 管理员查看其他用户
    username = viewUsername;
  } else if (currentUsername == null) {
    response.sendRedirect("index.jsp");
    return;
  }

  // 获取用户信息
  String email = "";
  String phone = "";
  String role = "";
  try {
    Class.forName("com.mysql.cj.jdbc.Driver");
    Connection conn = DriverManager.getConnection(
            "jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC",
            "root", "123456");

    String sql = "SELECT email, phone, user_role FROM users WHERE username = ?";
    PreparedStatement ps = conn.prepareStatement(sql);
    ps.setString(1, username);
    ResultSet rs = ps.executeQuery();

    if (rs.next()) {
      email = rs.getString("email");
      phone = rs.getString("phone");
      role = rs.getString("user_role");
    }

    rs.close();
    ps.close();
    conn.close();
  } catch (Exception e) {
    e.printStackTrace();
  }
%>

<div class="header">
  <div class="username">
    <%= username %>
    <% if ("admin".equals(role)) { %>
    <span class="role-tag">(管理员)</span>
    <% } %>
  </div>
  <% if (username.equals(currentUsername) || "admin".equals(currentRole)) { %>
  <button class="edit-btn" onclick="openEditModal()">修改信息</button>
  <% } %>
</div>

<!-- 修改信息模态框 -->
<div id="editModal" class="modal">
  <div class="modal-content">
    <span class="close" onclick="closeEditModal()">&times;</span>
    <h2>修改个人信息</h2>
    <form id="editForm">
      <div class="form-group">
        <label for="username">用户名:</label>
        <input type="text" id="username" name="username" value="<%= username %>" required>
      </div>
      <div class="form-group">
        <label for="email">邮箱:</label>
        <input type="email" id="email" name="email" value="<%= email != null ? email : "" %>" required>
      </div>
      <div class="form-group">
        <label for="phone">电话:</label>
        <input type="tel" id="phone" name="phone" value="<%= phone != null ? phone : "" %>" required>
      </div>
      <button type="button" class="save-btn" onclick="saveUserInfo()">保存修改</button>
    </form>
  </div>
</div>

<div class="history-header" onclick="toggleHistory()">
  <h3>历史记录</h3>
  <span id="historyArrow">▼</span>
</div>

<div id="historyContent" class="history-content">
  <table>
    <tr>
      <th>时间</th>
      <th>视频名称</th>
      <th>受灾建筑</th>
      <th>受灾人数</th>
      <th>受灾树木</th>
      <th>操作</th>
    </tr>

    <%
      Connection conn = null;
      PreparedStatement ps = null;
      ResultSet rs = null;

      try {
        Class.forName("com.mysql.cj.jdbc.Driver");
        conn = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC",
                "root", "123456"
        );

        String sql = "SELECT * FROM video_analysis WHERE username = ?";
        ps = conn.prepareStatement(sql);
        ps.setString(1, username);
        rs = ps.executeQuery();

        while (rs.next()) {
    %>
    <tr>
      <td><%= rs.getString("analysis_time") %></td>
      <td><%= rs.getString("video_name") %></td>
      <td><%= rs.getInt("damaged_building") %></td>
      <td><%= rs.getInt("damaged_person") %></td>
      <td><%= rs.getInt("damaged_tree") %></td>
      <td>
        <% if (username.equals(currentUsername)) { %>
        <button class="delete-btn" onclick="deleteRecord('<%= rs.getString("video_name") %>')">删除</button>
        <% } %>
      </td>
    </tr>
    <%
        }
      } catch (Exception e) {
        e.printStackTrace();
      } finally {
        if (rs != null) rs.close();
        if (ps != null) ps.close();
        if (conn != null) conn.close();
      }
    %>
  </table>
</div>

<% if (username.equals(currentUsername)) { %>
<button class="logout-btn" onclick="logout()">退出登录</button>
<% } %>

<!-- 底部导航栏 -->
<div class="bottom-nav">
  <a href="upload.jsp">首页</a>
  <a href="profile.jsp">个人信息</a>
</div>

<script>
  // 打开修改信息模态框
  function openEditModal() {
    document.getElementById('editModal').style.display = 'block';
  }

  // 关闭修改信息模态框
  function closeEditModal() {
    document.getElementById('editModal').style.display = 'none';
  }

  // 保存用户信息
  function saveUserInfo() {
    const form = document.getElementById('editForm');
    const formData = new FormData(form);

    // 验证表单
    for (let [key, value] of formData.entries()) {
      if (!value.trim()) {
        alert(key + '不能为空');
        return;
      }
    }

    fetch('updateUserServlet', {
      method: 'POST',
      body: formData
    })
            .then(response => {
              if (response.ok) {
                return response.text();
              }
              throw new Error('更新失败');
            })
            .then(message => {
              alert(message);
              closeEditModal();
              location.reload(); // 刷新页面
            })
            .catch(error => {
              alert(error.message);
            });
  }

  // 切换历史记录显示
  function toggleHistory() {
    const content = document.getElementById('historyContent');
    const arrow = document.getElementById('historyArrow');
    if (content.style.display === 'block') {
      content.style.display = 'none';
      arrow.textContent = '▼';
    } else {
      content.style.display = 'block';
      arrow.textContent = '▲';
    }
  }

  // 删除记录
  function deleteRecord(videoName) {
    if (confirm('确定要删除"' + videoName + '"这条记录吗？')) {
      fetch('deleteServlet', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'videoName=' + encodeURIComponent(videoName)
      })
              .then(response => {
                if (response.ok) {
                  return response.text();
                }
                throw new Error('删除失败');
              })
              .then(message => {
                alert(message);
                location.reload(); // 刷新页面
              })
              .catch(error => {
                alert(error.message);
              });
    }
  }

  // 退出登录
  function logout() {
    if (confirm('确定要退出登录吗？')) {
      fetch('logoutServlet', {
        method: 'POST'
      })
              .then(() => {
                window.location.href = 'index.jsp';
              })
              .catch(error => {
                alert('退出登录失败: ' + error.message);
              });
    }
  }
</script>

</body>
</html>
